package com.burgeon.backend.EnterpriseWeChat.controller;


import com.burgeon.backend.EnterpriseWeChat.service.EWChatService;
import com.burgeon.backend.EnterpriseWeChat.utils.EWCheckUtil;
import com.burgeon.backend.SHOPBACKEND.controller.BaseController;
import com.burgeon.backend.SHOPBACKEND.entity.recored.MessageRecore;
import com.burgeon.backend.SHOPBACKEND.entity.weixin.TextMessage;
import com.burgeon.backend.SHOPBACKEND.service.AWechatService;
import com.burgeon.backend.SHOPBACKEND.service.RecordService;
import com.burgeon.backend.Util.menu.WeChatInfo;
import com.burgeon.backend.Util.wechatUtil.CheckUtil;
import com.burgeon.backend.Util.wechatUtil.WechatMessageUtil;
import com.burgeon.backend.stsutil.ResponseResult;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@Controller
public class EWChatController extends EWBaseController{

    private static Logger log = Logger.getLogger(EWChatController.class);

    @Autowired
    private  EWChatService ewChatService;


    @RequestMapping("wechat/{token}")
    public void cgi(HttpServletRequest request, HttpServletResponse response,PrintWriter out, @PathVariable("token") String token) {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        try {
            if (isGet) {
                String signature = request.getParameter("signature");
                // 时间戳
                String timestamp = request.getParameter("timestamp");
                // 随机数
                String nonce = request.getParameter("nonce");
                // 随机字符串
                String echostr = request.getParameter("echostr");
                log.info("signature = "+signature+" , timestamp = "+timestamp+ " , nonce = "+nonce+ " , echostr = "+echostr);
                if (EWCheckUtil.checkSignature(signature, timestamp, nonce,token)) {
                    out.print(echostr);
                }
            }else{
                // 进入POST聊天处理
                // 将请求、响应的编码均设置为UTF-8（防止中文乱码）
                request.setCharacterEncoding("UTF-8");
                response.setCharacterEncoding("UTF-8");
                // 接收消息并返回消息
                response.setContentType("text/xml,charset=utf-8");
                Map<String, String> requestMap = WechatMessageUtil.xmlToMap(request);
                log.info(">>>>>>>>>>>>>"+requestMap);
                // 发送方帐号（open_id）
                String fromUserName = requestMap.get("FromUserName");
                // 公众帐号
                String toUserName = requestMap.get("ToUserName");
                TextMessage textMessage = new TextMessage();
                textMessage.setMsgType("text");
                textMessage.setToUserName(fromUserName);
                textMessage.setFromUserName(toUserName);
                textMessage.setCreateTime(System.currentTimeMillis());
                textMessage.setContent("success");
                String responseMessage = WechatMessageUtil.textMessageToXml(textMessage);

                out.print(responseMessage);
                out.flush();
                //处理请求
//              String rm = wechatService.processRequest(request);
                String rm = ewChatService.acceptMessage(requestMap, response, token);
                out.print(rm);

                // 响应消息
//              PrintWriter out = response.getWriter();
//              out.print(result);
                out.close();
            }
        } catch (Exception ex) {
            log.error("微信帐号接口配置失败！", ex);
            ex.printStackTrace();
        }
    }



}
